import { useState, useEffect } from 'react';
import api from '../api/axiosConfig';
import useAuthStore from '../store/authStore';
import { Link } from 'react-router-dom';
import axios from 'axios'; // 【FIX】Import axios

// This type definition can be moved to a central types.ts file later
interface Team {
    _id: string;
    name: string;
    owner: string;
    members: { _id: string; username: string; }[];
}

const MyTeamsPage = () => {
    const [myTeams, setMyTeams] = useState<Team[]>([]);
    const [loading, setLoading] = useState(true);
    const { userInfo } = useAuthStore();

    useEffect(() => {
        const fetchMyTeams = async () => {
            try {
                const { data } = await api.get('/users/profile');
                setMyTeams(data.teams || []);
            } finally {
                setLoading(false);
            }
        };
        if (userInfo) fetchMyTeams();
    }, [userInfo]);

    if (loading) return <p>Loading...</p>;

    return (
        <div style={{ maxWidth: '800px', margin: '0 auto' }}>
            <h2>My Teams</h2>
            <Link to="/create-team">Create New Team</Link>
            <hr />
            {myTeams.length > 0 ? (
                myTeams.map(team => (
                    <div key={team._id} style={{ border: '1px solid #ccc', padding: '1rem', marginBottom: '1rem' }}>
                        <h3>{team.name}</h3>
                        <p>Members: {team.members.map(m => m.username).join(', ')}</p>
                        {userInfo?._id === team.owner && <AddMemberForm teamId={team._id} />}
                    </div>
                ))
            ) : (
                <p>You have not joined any teams yet.</p>
            )}
        </div>
    );
};

// Add Member Form Sub-Component
const AddMemberForm = ({ teamId }: { teamId: string }) => {
    const [email, setEmail] = useState('');
    const [message, setMessage] = useState('');

    const handleAddMember = async (e: React.FormEvent) => {
        e.preventDefault();
        setMessage('');
        try {
            await api.post(`/teams/${teamId}/members`, { email });
            setMessage(`Successfully invited ${email}! Refresh the page to see updates.`);
            setEmail('');
        } catch (err) {
            // 【FIX】Use the axios type guard
            if (axios.isAxiosError(err)) {
                setMessage(err.response?.data?.message || 'Failed to invite');
            } else {
                setMessage('An unknown error occurred');
            }
        }
    };
    
    return (
        <form onSubmit={handleAddMember} style={{ marginTop: '1rem', borderTop: '1px solid #eee', paddingTop: '1rem' }}>
            <h4>Invite New Member</h4>
            <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="Enter member's email" required />
            <button type="submit">Add</button>
            {message && <p>{message}</p>}
        </form>
    );
};

export default MyTeamsPage;